<template>
  <div>
    <van-nav-bar
      title="商品搜索"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-search
      v-model="keyWord"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      :autofocus="true"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!--搜索历史tag-->
    <div class="history" v-if="history">
      <div class="title">
        <div>搜索历史</div>
        <van-icon name="delete-o" @click="clearHistory"/>
      </div>
      <div style="display: flex ; flex-wrap: wrap;">
        <van-tag
          class="tag"
          color="#f2f2f2"
          size="large"
          text-color="black"
          v-for="(item,index) in history"
          :key="index"
          @click="checkHistory(item,index)"
        >
          <span>{{ item }}</span>
        </van-tag>
      </div>
    </div>
  </div>
</template>

<script>
import { setHistory, getHistory } from '@/utils/storage'

export default {
  name: 'search-index',
  data () {
    return {
      keyWord: '',
      history: getHistory()
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    onSearch () {
      if (this.keyWord.length === 0) {
        return
      }
      const index = this.history.indexOf(this.keyWord)
      if (index > 0) {
        this.history.splice(index, 1)
      }
      if (this.history.length > 10) {
        this.history = this.history.slice(-9)
      }
      this.history.unshift(this.keyWord)
      setHistory(this.history)
      this.$router.push(`/searchlist?search=${this.keyWord}`)
    },
    checkHistory (item, index) {
      // this.keyWord = item
      this.history.splice(index, 1) // 移除搜索历史中已存在的关键词
      this.history.unshift(item) // 将当前搜索关键词添加到搜索历史的开头
      setHistory(this.history)
      this.$router.push(`/searchlist?search=${item}`) // 跳转到搜索结果页面
    },
    // 清空历史框
    clearHistory () {
      this.history = []
      setHistory(this.history)
    }
  }
}
</script>

<style>
.history {
  .title {
    margin: 5px 20px;
    border-bottom: 1px solid #999999;
    display: flex;
    justify-content: space-between;
    align-content: center;
  }

  .tag {
    margin: 5px 5px;
  }
}
</style>
